var height = window.screen.height - 250;
if (top.Rsd) {
    height = top.Rsd.getUrlParam(window.location.search.substr(1), "h");
}
if (top.Rsd && top.Rsd.isMobile()) {
    //document.getElementById('outpane').style.fontSize = '200%';
    //document.getElementById('sidebar').style.display="none";
}

mermaid.initialize({
    startOnLoad: false, //true:自动开始渲染页面上所有的 <pre class="mermaid">图形代码</pre> 图表块
    theme: 'forest', //设置主题为暗色主题,支持 default、forest、dark  
    flowchart: {
        curve: 'cardinal'//可选 linear（直线）、curve（贝塞尔曲线）、cardinal（折线）。
    },
    sequence: {
        actorMargin: 50//‌时序图参与者间距‌,调整参与者之间的间隔
    },
    fontFamily: '"Microsoft YaHei", sans-serif',
    securityLevel: 'strict',//'strict'（默认）:单击功能被禁用、'antiscript':启用单击功能、'loose':允许文本中包含 HTML 标签，并启用单击功能、'sandbox':所有渲染都在沙盒 iframe 中进
    maxTextSize: 10000
});

//console.debug('添加一个mermaid renderer，用于支持流程图');

const renderer = new marked.Renderer();
renderer.code = function (data) {
    //console.log('code', arguments);
    var _html_code = ""
    if (data.lang === 'mermaid') {

        var _chart_id = "rsd_chart_" + Date.now();
        //自定义 图像占位符
        _html_code =  `<div id='${_chart_id}' style="color:red;" class="mermaid">{正在生成图形...}</div>\n`;
  
        //将图表 渲染到dom控件上
        mermaidRender(_chart_id + '_svg', data.text).then(function(resp){

          //console.log(resp);
            //处理生成的SVG代码，例如将其插入到指定的div中
           var svg_code = resp.svg;
           var diagramType = resp.diagramType;
           //var  bindFunctions = resp.bindFunctions; 
           document.getElementById(_chart_id).innerHTML = svg_code;  
         })
         .catch(function(err){
             console.error(err);
         }); ; 
    }
    else {
        _html_code = data.text;
    }

    //console.log('_html_code',_html_code);

    return _html_code; // 默认处理
};

const highlight = function (code, type) {
    console.log('high-light', type);

    if (type === 'mermaid') {
        var _chart_id = "rsd_chart_" + Date.now();
        this.count++
        mermaid.render(_chart_id, code)
        .then(
            function (resp) { 
                //console.log(resp);
                //输出 SVG 代码，
                var svg_code = resp.svg;
                var diagramType = resp.diagramType;
                //var bindFunctions = resp.bindFunctions;
                document.getElementById(_chart_id).innerHTML = svg_code; 
            })
            .catch(function (err) {
                console.error(err);
            }
        )
        .catch(function (err) {
                console.error(err);
            });

        return `<div class="language-mermaid" id='${_chart_id}'>${code}</div>`;
    }

    return hljs.highlightAuto(code).value;
};

const options = {
    "renderer": renderer,
    "highlight": highlight,
    "async": false,
    "breaks": false,
    "extensions": null,
    "gfm": true,
    "hooks": null,
    "pedantic": false,
    "silent": false,
    "tokenizer": null,
    "walkTokens": null
};

marked.setOptions(options);
 
async function mermaidRender(id,md_code,callback)
{
  
  try {
    var rs = await mermaid.parse(md_code, { suppressErrors: false });
    
    if (!rs) {
      svg_code = 'mermaid Error';
    }
  }
  catch (err) {
    svg_code = err.message;
  }
 //将图表 渲染到dom控件上
  return mermaid.render(id, md_code,callback); 
        
}

 
var render = function (markdown, callback) {
 
    var div = document.getElementById('outpane');
    if (div) {
        div.innerHTML = ""; 
        delayTime = 100; 
        const startTime = new Date();
        const lexed = marked.lexer(markdown);//, options
        //const lexedList = jsonString(lexed);  //内部使用的标签，可以用于生成文档目录结构
        //console.log(lexedList); 
        const parsed = marked.parser(lexed);//, options
        const endTime = new Date();
        div.innerHTML = parsed;
       
        delayTime = 10;
        document.getElementById('loading').style.display = 'none';
        document.getElementById('main').style.display = 'block';
 
        if (callback) {
            callback();
        }
    }

};

var hideSidebar = function hideSidebar() {
    document.getElementById('sidebar').style.width = '30px';
}

/**
 * 
 * @param {*} e 
 */
document.onreadystatechange = function (e) {
    //console.log(e);
    // const message = document.readyState + " from editor.html!";
    // const targetOrigin = "*"; // 可以指定父页面的源，例如 "http://example.com"
    // window.parent.postMessage(message, targetOrigin);
   //
   if(document.readyState == 'complete')
   {
       var view = document.getElementById('outpane');
        if (view) {
            view.onclick = hideSidebar;

            document.body.addEventListener('touchmove', function (e) {
                //e.preventDefault(); 
            }, { passive: false });
        }
       
        fetch(top.Rsd.getRedjsUrl('plugin/marked/app/initial.md'))
            .then(res => res.text())
            .then(text => {
                window.render(text)
            });
   }
    
}

 